<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
           <el-form-item label="平台类型" prop="platId">
            <el-select v-model="searchInfo.platId" clearable placeholder="请选择" @clear="()=>{searchInfo.platId=undefined}">
              <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
        <el-form-item label="包名" prop="appId">
         <el-input v-model="searchInfo.appId" placeholder="搜索条件"  />

        </el-form-item>
        <el-form-item label="渠道名" prop="channelId">
         <el-input v-model="searchInfo.channelId" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="产品标识" prop="productId">
         <el-input v-model="searchInfo.productId" placeholder="搜索条件" />

        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
         <el-input v-model="searchInfo.productName" placeholder="搜索条件" />

        </el-form-item>
           <el-form-item label="产品类型" prop="type">
            <el-select v-model="searchInfo.type" clearable placeholder="请选择" @clear="()=>{searchInfo.type=undefined}">
              <el-option v-for="(item,key) in productTypeOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
           <el-form-item label="状态" prop="status">
            <el-select v-model="searchInfo.status" clearable placeholder="请选择" @clear="()=>{searchInfo.status=undefined}">
              <el-option v-for="(item,key) in productStatusOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <div class="gva-btn-list">
            <el-button type="primary" icon="plus" @click="openDialog">新增</el-button>
            <el-popover v-model:visible="deleteVisible" :disabled="!multipleSelection.length" placement="top" width="160">
            <p>确定要删除吗？</p>
            <div style="text-align: right; margin-top: 8px;">
                <el-button type="primary" link @click="deleteVisible = false">取消</el-button>
                <el-button type="primary" @click="onDelete">确定</el-button>
            </div>
            <template #reference>
                <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="deleteVisible = true">删除</el-button>
            </template>
            </el-popover>
        </div>
        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="ID"
        @selection-change="handleSelectionChange"
        >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="ID" prop="ID" width="180" />

        <el-table-column align="left" label="产品名称" prop="productName" width="120" />
        <el-table-column align="left" label="档位描述" prop="description" width="120" />
        <el-table-column align="left" label="档位底色" prop="backgroundColor" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.backgroundColor,productBackgroundColorOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="原价" prop="originCost" width="120">
            <template #default="scope">{{  scope.row.originCost>0 ?(scope.row.originCost/100).toFixed(2)+" 元": "0 元"}}</template>
         </el-table-column>
        <el-table-column align="left" label="实际价格（分）" prop="cost" width="120" />
        <el-table-column align="left" label="看点（个）" prop="amount" width="120" >
            <template #default="scope">{{  scope.row.type==1&& scope.row.amount>0?(scope.row.amount): "0"}}</template>
         </el-table-column>
        <el-table-column align="left" label="赠送看点（个）" prop="give" width="120" >
            <template #default="scope">{{  scope.row.type==1&& scope.row.give>0?(scope.row.give): "0"}}</template>
         </el-table-column>
        <el-table-column align="left" label="VIP天数" prop="amount" width="120">
            <template #default="scope">{{  scope.row.type==2&& scope.row.amount>0?(scope.row.amount/86400).toFixed(2)+" 天": "0 天"}}</template>
         </el-table-column>
        <el-table-column align="left" label="角标描述" prop="logoDesc" width="120" />
        <el-table-column align="left" label="角标样式" prop="logoStyle2" width="120">
          <template #default="scope">
            {{ filterDict(scope.row.logoStyle2,productLogoStyleOptions) }}
            </template>
        </el-table-column>
        <!-- <el-table-column align="left" label="档位配置分类" prop="mode" width="120" /> -->
        <el-table-column align="left" label="产品类型" prop="type" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.type,productTypeOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="状态" prop="status" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.status,productStatusOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="平台类型" prop="platId" width="120">
            <template #default="scope">
            {{ filterDict(scope.row.platId,platOptions) }}
            </template>
        </el-table-column>
        <el-table-column align="left" label="包名" prop="appId" width="120" />
        <!-- <el-table-column align="left" label="渠道名" prop="channelId" width="120" /> -->
        <!-- <el-table-column align="left" label="排序" prop="orderNum" width="120" /> -->
        <el-table-column align="left" label="产品标识" prop="productId" width="120" />

        <el-table-column align="left" label="创建人" prop="createUid" width="120" />
         <el-table-column align="left" label="创建时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.createTime) }}</template>
         </el-table-column>
        <!-- <el-table-column align="left" label="更新人" prop="updateUid" width="120" />
         <el-table-column align="left" label="更新时间" width="180">
            <template #default="scope">{{ formatDate(scope.row.updateTime) }}</template>
         </el-table-column> -->
        <el-table-column align="left" label="操作"   fixed="right" width="120">
            <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getDetails(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                查看详情
            </el-button>
            <el-button type="primary" link icon="edit" class="table-button" @click="updateTProductFunc(scope.row)">变更</el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>
    <el-dialog v-model="dialogFormVisible" :before-close="closeDialog" :title="type==='create'?'添加':'修改'" destroy-on-close>
      <el-scrollbar height="540px">
          <el-form :model="formData" label-position="right" ref="elFormRef" :rules="rule" label-width="140px">
            <el-form-item label="平台类型:"  prop="platId" v-show="true">
              <el-select v-model="formData.platId" placeholder="请选择平台类型" style="width:100%" :clearable="false" >
                <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="包名:"  prop="appId"  v-show="false">
              <el-input v-model="formData.appId" :clearable="true"  placeholder="请输入包名" />
            </el-form-item>
            <!-- <el-form-item label="渠道名:"  prop="channelId" >
              <el-input v-model="formData.channelId" :clearable="true"  placeholder="请输入渠道名" />
            </el-form-item> -->
            <!-- <el-form-item label="排序:"  prop="orderNum" >
              <el-input v-model.number="formData.orderNum" :clearable="true" placeholder="请输入排序" />
            </el-form-item> -->
            <!-- <el-form-item label="产品标识:"  prop="productId" >
              <el-input v-model="formData.productId" :clearable="true"  placeholder="请输入产品标识" />
            </el-form-item> -->
            <el-form-item label="产品名称:"  prop="productName" >
              <el-input v-model="formData.productName" :clearable="true"  placeholder="请输入产品名称" maxlength="20"/>
            </el-form-item>
            <el-form-item label="档位描述:"  prop="description" >
              <el-input v-model="formData.description" :clearable="true"  placeholder="请输入档位描述(最多8个字)" maxlength="8" />
            </el-form-item>
            <el-form-item label="档位底色:"  prop="backgroundColor" >
              <el-radio-group v-model.number="formData.backgroundColor" >
                <el-radio v-for="(item,key) in productBackgroundColorOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="原价(元):"  prop="originCostFloat" >
              <el-input v-model.trim="formData.originCostFloat" :clearable="true" placeholder="请输入原价(单位元，最多两位小数)"  @input="limitInput"  />
            </el-form-item>
            <el-form-item label="实际价格（分）:"  prop="cost" v-show="false">
              <el-input v-model.number="formData.cost"  placeholder="" :disabled = "true" />
            </el-form-item>
            <el-form-item label="产品类型:"  prop="type">
              <el-radio-group v-model.number="formData.type"  :disabled = "type==='create'?false:true" @change="ChangeType"   >
                <el-radio v-for="(item,key) in productTypeOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="看点（个）:"  prop="amount" v-if="formData.type===1">
              <el-input v-model.number="formData.amount" :clearable="true" placeholder="充值看点（个）"  :disabled = "true" />
            </el-form-item>
            <el-form-item label="赠送看点（个）:"  prop="give" v-if="formData.type===1">
              <el-input v-model.number="formData.give" :clearable="true" placeholder="请输入赠送看点（个）" type="number" />
            </el-form-item>
            <el-form-item label="vip（档位）:"  prop="amount" v-if="formData.type===2">
              <el-radio-group v-model.number="formData.amount"    @change="ChangeProductVipOptions"  >
                <el-radio v-for="(item,key) in productVipOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="VIP描述开关:" v-auth="btnAuth.vipDescStatus"  prop="vipDescStatus" v-if="formData.type===2" >
              <el-radio-group v-model.number="formData.vipDescStatus"     >
                <el-radio v-for="(item,key) in switchOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="VIP描述:" v-auth="btnAuth.vipDescStatus"  prop="vipDesc" v-if="formData.type===2" >
              <el-input v-model="formData.vipDesc" :clearable="true"  placeholder="请输入VIP描述(最多8个字)"  maxlength="8" />
            </el-form-item>
            <el-form-item label="角标描述:"  prop="logoDesc" >
              <el-input v-model="formData.logoDesc" :clearable="true"  placeholder="请输入角标描述(最多7个字)"  maxlength="7" />
            </el-form-item>
            <el-form-item label="角标样式:"  prop="logoStyle2" >
              <el-select v-model="formData.logoStyle2" placeholder="请选择角标样式" style="width:100%"  >
                <el-option v-for="(item,key) in productLogoStyleOptions" :key="key" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>

            <el-form-item label="状态:"  prop="status" >
              <el-radio-group v-model.number="formData.status"    >
                <el-radio v-for="(item,key) in productStatusOptions" :key="item.value" :label="item.value" :value="item.value" >{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>

          </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button type="primary" @click="enterDialog">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="detailShow" style="width: 800px" lock-scroll :before-close="closeDetailShow" title="查看详情" destroy-on-close>
      <el-scrollbar height="550px">
        <el-descriptions column="1" border>
                <el-descriptions-item label="平台类型">
                        {{ filterDict(formData.platId,platOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="包名">
                        {{ formData.appId }}
                </el-descriptions-item>
                <el-descriptions-item label="渠道名">
                        {{ formData.channelId }}
                </el-descriptions-item>
                <el-descriptions-item label="排序">
                        {{ formData.orderNum }}
                </el-descriptions-item>
                <el-descriptions-item label="产品标识">
                        {{ formData.productId }}
                </el-descriptions-item>
                <el-descriptions-item label="产品名称">
                        {{ formData.productName }}
                </el-descriptions-item>
                <el-descriptions-item label="档位描述">
                        {{ formData.description }}
                </el-descriptions-item>
                <el-descriptions-item label="档位底色">
                        {{ filterDict(formData.backgroundColor,productBackgroundColorOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="原价">
                        {{ formData.originCost }}
                </el-descriptions-item>
                <el-descriptions-item label="实际价格（分）">
                        {{ formData.cost }}
                </el-descriptions-item>
                <el-descriptions-item label="看点（个）">
                        {{ formData.amount }}
                </el-descriptions-item>
                <el-descriptions-item label="赠送看点（个）">
                        {{ formData.give }}
                </el-descriptions-item>
                <el-descriptions-item label="角标描述">
                        {{ formData.logoDesc }}
                </el-descriptions-item>
                <el-descriptions-item label="角标样式">
                        {{ filterDict(formData.logoStyle2,productLogoStyleOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="档位场景类型：1通用, 2定制短剧档位库">
                        {{ formData.mode }}
                </el-descriptions-item>
                <el-descriptions-item label="类型">
                        {{ filterDict(formData.type,productTypeOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="状态">
                        {{ filterDict(formData.status,productStatusOptions) }}
                </el-descriptions-item>
                <el-descriptions-item label="创建人">
                        {{ formData.createUid }}
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">
                      {{ formatDate(formData.createTime) }}
                </el-descriptions-item>
                <el-descriptions-item label="更新人">
                        {{ formData.updateUid }}
                </el-descriptions-item>
                <el-descriptions-item label="更新时间">
                      {{ formatDate(formData.updateTime) }}
                </el-descriptions-item>
        </el-descriptions>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createTProduct,
  deleteTProduct,
  deleteTProductByIds,
  updateTProduct,
  findTProduct,
  getTProductList
} from '@/api/tProduct'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'

defineOptions({
    name: 'TProduct'
})

//引用菜单按钮权限组件
import { useBtnAuth } from '@/utils/btnAuth'
    const btnAuth = useBtnAuth()

// 自动化生成的字典（可能为空）以及字段
const platOptions = ref([])
const productBackgroundColorOptions = ref([])
const productLogoStyleOptions = ref([])
const productTypeOptions = ref([])
const productStatusOptions = ref([])
const productVipOptions = ref([])
const switchOptions = ref([])
const productVipDescOptions = ref([])

const formData = ref({
        platId: '',
        appId: 'com.wyxh.wanyi',
        channelId: '',
        orderNum: 0,
        productId: '',
        productName: '',
        description: '',
        backgroundColor: undefined,
        originCost: '',
        originCostFloat: '',
        cost: '',
        amount: '',
        give: 0,
        logoDesc: '',
        logoStyle2: 0,
        vipDesc:'',
        vipDescStatus:1,
        mode: 2,
        type: 1,
        status: 1,
        createUid: 0,
        createTime: '',
        updateUid: 0,
        updateTime: '',
        })

const originCostFloatMinMax =  (rule, value, callback) => {
  if(value>400|| value<1) {
    callback('超出限制')
  } else {
    callback()
  }
}
const giveMinMax =  (rule, value, callback) => {
  if(value>20000|| value<0) {
    callback('超出限制')
  } else {
    callback()
  }
}
const amountMin =  (rule, value, callback) => {
  if(value<=0) {
    callback('超出限制')
  } else {
    callback()
  }
}
// 验证规则
const rule = reactive({
               platId : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
               appId : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
              //  channelId : [{
              //      required: true,
              //      message: '',
              //      trigger: ['input','blur'],
              //  },
              //  {
              //      whitespace: true,
              //      message: '不能只输入空格',
              //      trigger: ['input', 'blur'],
              // }
              // ],
               orderNum : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
              //  productId : [{
              //      required: true,
              //      message: '',
              //      trigger: ['input','blur'],
              //  },
              //  {
              //      whitespace: true,
              //      message: '不能只输入空格',
              //      trigger: ['input', 'blur'],
              // }
              // ],
               productName : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               {
                   whitespace: true,
                   message: '不能只输入空格',
                   trigger: ['input', 'blur'],
              }
              ],
               originCost : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
              originCostFloat : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
               { validator: originCostFloatMinMax, message: '原价范围1-400',trigger: 'blur'} 
              ],
              give : [
               { validator: giveMinMax, message: '赠点范围0-20000',trigger: 'blur'} 
              ],
               cost : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
               amount : [{
                   required: true,
                   message: '请选择vip档位',
                   trigger: ['input','blur'],
               },
               { validator: amountMin, message: '请选择vip档位',trigger: 'blur'} 
              ],
               type : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
               status : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getTProductList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
    platOptions.value = await getDictFunc('plat')
    productBackgroundColorOptions.value = await getDictFunc('productBackgroundColor')
    productLogoStyleOptions.value = await getDictFunc('productLogoStyle')
    productTypeOptions.value = await getDictFunc('productType')
    productStatusOptions.value = await getDictFunc('productStatus')
    productVipOptions.value = await getDictFunc('productVip')
    switchOptions.value = await getDictFunc('switch')
    productVipDescOptions.value = await getDictFunc('productVipDesc')

}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteTProductFunc(row)
        })
    }


// 批量删除控制标记
const deleteVisible = ref(false)

// 多选删除
const onDelete = async() => {
      const ids = []
      if (multipleSelection.value.length === 0) {
        ElMessage({
          type: 'warning',
          message: '请选择要删除的数据'
        })
        return
      }
      multipleSelection.value &&
        multipleSelection.value.map(item => {
          ids.push(item.ID)
        })
      const res = await deleteTProductByIds({ ids })
      if (res.code === 0) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })
        if (tableData.value.length === ids.length && page.value > 1) {
          page.value--
        }
        deleteVisible.value = false
        getTableData()
      }
    }

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')
// 控制vip表单元素展示
let fromRadioTypeVIP = ref(false)
// 控制看点+赠点表单元素展示
let fromInputTypeYUEBI = ref(false)

// 更新行
const updateTProductFunc = async(row) => {
    const res = await findTProduct({ ID: row.ID })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data.retProduct
        formData.value.originCostFloat = formData.value.originCost/100

        dialogFormVisible.value = true
    }
}


// 删除行
const deleteTProductFunc = async (row) => {
    const res = await deleteTProduct({ ID: row.ID })
    if (res.code === 0) {
        ElMessage({
                type: 'success',
                message: '删除成功'
            })
            if (tableData.value.length === 1 && page.value > 1) {
            page.value--
        }
        getTableData()
    }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)


// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开详情
const getDetails = async (row) => {
  // 打开弹窗
  const res = await findTProduct({ ID: row.ID })
  if (res.code === 0) {
    formData.value = res.data.retProduct
    formData.value.originCost = formData.value.originCost/100

    openDetailShow()
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
          platId: '',
          appId: '',
          channelId: '',
          orderNum: 0,
          productId: '',
          productName: '',
          description: '',
          backgroundColor: undefined,
          originCost: '',
          originCostFloat: '',
          cost: '',
          amount: '',
          give: 0,
          logoDesc: '',
          logoStyle2: 0,
          vipDesc:'',
          vipDescStatus:1,
          mode: 2,
          type: undefined,
          status: undefined,
          createUid: 0,
          createTime: '',
          updateUid: 0,
          updateTime: '',
          }
}


// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true

}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        platId: '',
        appId: 'com.wyxh.wanyi',
        channelId: '',
        orderNum: 0,
        productId: '',
        productName: '',
        description: '',
        backgroundColor: undefined,
        originCost: '',
        cost: '',
        amount: 0,
        give: 0,
        logoDesc: '',
        logoStyle2: 0,
        vipDesc:'',
        vipDescStatus:1,
        mode: 2,
        type: 1,
        status: 1,
        createUid: 0,
        createTime: '',
        updateUid: 0,
        updateTime: '',
        }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return
              let res
              switch (type.value) {
                case 'create':
                  res = await createTProduct(formData.value)
                  break
                case 'update':
                  res = await updateTProduct(formData.value)
                  break
                default:
                  res = await createTProduct(formData.value)
                  break
              }
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}


const ChangeType = async (e)  => {

  if (e==1&&type.value==='create'){
    formData.value.amount=''
    formData.value.vipDesc=''

    if (formData.value.originCostFloat>0 ) {
      formData.value.amount = Math.round(formData.value.originCostFloat*100)
    }
  }
  if (e==2&&type.value==='create'){
    formData.value.amount=''
  }
}

const limitInput= (value) => {
      formData.value.originCostFloat =
        ("" + value) // 第一步：转成字符串
          .replace(/[^\d^\.]+/g, "") // 第二步：把不是数字，不是小数点的过滤掉
          .replace(/^0+(\d)/, "$1") // 第三步：第一位0开头，0后面为数字，则过滤掉，取后面的数字
          .replace(/^\./, "0.") // 第四步：如果输入的第一位为小数点，则替换成 0. 实现自动补全
          .match(/^\d*(\.?\d{0,2})/g)[0] || ""; // 第五步：最终匹配得到结果 以数字开头，只有一个小数点，而且小数点后面只能有0到2位小数
      
          formData.value.originCost = Math.round(formData.value.originCostFloat*100)
          formData.value.cost = Math.round(formData.value.originCostFloat*100)
          if (formData.value.type ===1){
            formData.value.amount = Math.round(formData.value.originCostFloat*100)
          }

    }
const ChangeProductVipOptions = async (e)  => {
  productVipDescOptions.value.forEach(item => {
    if(e==item.value){
      formData.value.vipDesc=item.label
    }
})
  // if (e==1&&type.value==='create'){
  //   formData.value.amount=''
  // }
}    
</script>

<style>

</style>
